/**
 * @author LKQ
 * @date 2022/4/4 8:15
 * @description O(n)时间复杂度超时，方法一：分块模拟，将数组nums分成多个块，每块的大小为size ( size = Sqrt(nums.length)
 */
public class NumArray {
    /**
     * sum[i]为第i块大小的和
     */
    private int[] sum;
    /**
     * 块的大小
     */
    private int size;
    private int[] nums;
    public NumArray(int[] nums) {
        this.nums = nums;
        int n = nums.length;
        size = (int) Math.sqrt(n);
        // n / size 向上取整
        sum = new int[(n + size - 1) / size];
        for(int i = 0; i < n; i++) {
            sum[i / size] += nums[i];
        }
    }

    public void update(int index, int val) {
        sum[index / size] += val - nums[index];
        nums[index] = val;
    }

    public int sumRange(int left, int right) {
        int b1 = left / size, i1 = left % size, b2 = right / size, i2 = right % size;
        if (b1 == b2) {
            // 说明在同一个块内
            int sum = 0;
            for (int j = i1; j <= i2; j++) {
                sum += nums[b1 * size + j];
            }
            return sum;
        }
        // 不在同一块中，
        int sum1 = 0;
        for (int j = i1; j < size; j++) {
            sum1 += nums[b1 * size + j];
        }
        int sum2 = 0;
        for (int j = 0; j <= i2; j++) {
            sum2 += nums[b2 * size + j];
        }
        int sum3 = 0;
        for (int j = b1 + 1; j < b2; j++) {
            sum3 += sum[j];
        }
        return sum1 + sum2 + sum3;

    }
}
